package com.notary.tx_live_plugin;

import android.app.Activity;
import android.content.Context;

import androidx.annotation.NonNull;

import com.notary.tx_live_plugin.platform.PluginMethodCallHandlerImpl;
import com.notary.tx_live_plugin.platform.TxLivePlatformFactory;
import com.notary.tx_live_plugin.util.ChatManager;
import com.notary.tx_live_plugin.util.TxLogger;
import com.notary.tx_live_plugin.util.TxConstant;
import com.notary.tx_live_plugin.util.PushManager;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.platform.PlatformViewRegistry;

/** TxLivePlugin */
public class TxLivePlugin implements FlutterPlugin, ActivityAware {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private MethodChannel channel;
  private ActivityPluginBinding pluginBinding;
  @SuppressWarnings("deprecation")
  private PluginRegistry.Registrar pluginRegistrar;
  private final PushManager pushManager;

  public TxLivePlugin(){
    pushManager = PushManager.getInstance();
  }

  /**
   * Registers a plugin implementation that uses the stable {@code io.flutter.plugin.common}
   * package.
   */
  @SuppressWarnings("deprecation")
  public static void registerWith(io.flutter.plugin.common.PluginRegistry.Registrar registrar) {
    final TxLivePlugin plugin = new TxLivePlugin();
    plugin.pluginRegistrar = registrar;
    plugin.registerListeners();

    plugin.startListening(
            registrar.context(),
            registrar.messenger(),
            registrar.platformViewRegistry()
    );
    if (registrar.activeContext() instanceof Activity) {
      plugin.startListeningToActivity(registrar.activity());
    }
  }

  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
    startListening(
            flutterPluginBinding.getApplicationContext(),
            flutterPluginBinding.getBinaryMessenger(),
            flutterPluginBinding.getPlatformViewRegistry()
    );
  }

  @Override
  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
    stopListening();
  }

  /**
   * 开始注册factory、channel
   */
  public void startListening(Context context, BinaryMessenger messenger, PlatformViewRegistry platformViewRegistry) {
    TxLogger.setLogLevel(BuildConfig.DEBUG ? TxLogger.VERBOSE : TxLogger.ERROR);
    //该channel用于TxLive初始化
    channel = new MethodChannel(messenger, TxConstant.Channel.PLUGIN);
    channel.setMethodCallHandler(new PluginMethodCallHandlerImpl(context));
    platformViewRegistry.registerViewFactory(
            TxConstant.PLATFORM_FACTORY,
            new TxLivePlatformFactory(messenger)
    );
  }

  public void stopListening(){
    if(channel != null)channel.setMethodCallHandler(null);
    channel = null;
  }


  private void startListeningToActivity(Activity activity) {
    pushManager.setActivity(activity);
  }

  private void stopListeningToActivity() {
    pushManager.setActivity(null);
  }

  private void registerListeners() {
    if (this.pluginRegistrar != null) {
      this.pluginRegistrar.addRequestPermissionsResultListener(this.pushManager);
      this.pluginRegistrar.addRequestPermissionsResultListener(ChatManager.getInstance());
    } else if (pluginBinding != null) {
      this.pluginBinding.addRequestPermissionsResultListener(this.pushManager);
      this.pluginBinding.addRequestPermissionsResultListener(ChatManager.getInstance());
    }
  }

  private void unregisterListeners() {
    if (pluginBinding != null) {
      this.pluginBinding.removeRequestPermissionsResultListener(this.pushManager);
      this.pluginBinding.removeRequestPermissionsResultListener(ChatManager.getInstance());
    }
  }

  @Override
  public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
    startListeningToActivity(binding.getActivity());
    this.pluginBinding = binding;
    registerListeners();
  }

  @Override
  public void onDetachedFromActivityForConfigChanges() {
    onDetachedFromActivity();
  }

  @Override
  public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {
    onAttachedToActivity(binding);
  }

  @Override
  public void onDetachedFromActivity() {
    stopListeningToActivity();
    unregisterListeners();
  }
}
